package cn.com.dcsgo.validation.menu.validator.impl;

import cn.com.dcsgo.domain.SysMenu;
import cn.com.dcsgo.mapper.SysMenuMapper;
import cn.com.dcsgo.validation.menu.MenuType;
import cn.com.dcsgo.validation.menu.MenuValidationResult;
import cn.com.dcsgo.validation.menu.validator.MenuValidator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 子菜单校验器（菜单）
 *
 * @author Dcsgo
 * @since 2025/10/12 14:31
 */
@Component(MenuType.menu)
public class SubMenuValidator extends MenuValidator {
    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public void prepareValidate(Map<String, Object> validatorFields) {
        this.validatorFields = validatorFields;
        if (!validatorFields.containsKey("parentId")) {
            throw new IllegalArgumentException("目录校验必须包含parentId字段");
        }
        if (!validatorFields.containsKey("url")) {
            throw new IllegalArgumentException("目录校验必须包含url字段");
        }
        this.isReady = true;
    }

    @Override
    public MenuValidationResult validate() {
        if (!isReady) {
            throw new IllegalStateException("校验器未就绪，请先调用prepareValidate方法");
        }
        Long parentId = (Long) validatorFields.get("parentId");
        String url = (String) validatorFields.get("url");
        if (parentId == null || url == null) {
            return MenuValidationResult.failure("parentId和url不能为null");
        }
        if (parentId.equals(0L)) {
            return MenuValidationResult.failure("菜单类型的上级菜单请选择下拉菜单中一级菜单或二级菜单中的内容");
        }
        SysMenu parentMenu = sysMenuMapper.selectOne(new LambdaQueryWrapper<SysMenu>()
                .eq(SysMenu::getMenuId, parentId)
        );
        if (parentMenu == null) {
            return MenuValidationResult.failure("上级菜单不存在");
        }
        //允许创建多级子菜单
        if (MenuType.getMenuType(parentMenu.getType()).equals(MenuType.directory)
                || MenuType.getMenuType(parentMenu.getType()).equals(MenuType.menu)) {
            return MenuValidationResult.success();
        }
        return MenuValidationResult.failure("菜单类型的上级菜单请选择下拉菜单中一级菜单或二级菜单中的内容");
    }
}
